<!-- 实时数据监测 -->

<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowLeftBold } from '@element-plus/icons-vue'
import moment from 'moment'
import jkdwzs from '@/assets/image/dataMonitor/jkdwzs-icon.png'
import zcdw from '@/assets/image/dataMonitor/zcdw-icon.png'
import jgdw from '@/assets/image/dataMonitor/jgdw-icon.png'
import lxdw from '@/assets/image/dataMonitor/lxdw-icon.png'

/** tab start */
const tabActiveIndex = ref(0)
const nylx = ref('2') //能源类型

const topNav = reactive([
  { text: '园区电力监测', dm: '2', xzcs: 'dljc' },
  { text: '园区蒸汽监测', dm: '3', xzcs: 'zqjc' },
  { text: '园区水务监测', dm: '1', xzcs: 'swjc' },
  { text: '园区燃气监测', dm: '4', xzcs: 'rqjc' },
  { text: '园区用煤监测', dm: '5', xzcs: 'ymjc' },
])

//tab切换
const tabClick = (item: any, index: any) => {
  nylx.value = item.dm
  tabActiveIndex.value = index

  dialogVisible.value = false //关闭表格

  //时间重置
  formInline.sjfw = [
    moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    moment().format('YYYY-MM-DD HH:mm:ss'),
  ]

  getDictionary() //重新查询字典
  loadJcdwInfo() //重新查询监测点位
  getQylb() //重新查询企业数据
  // resetEchart() //重新查询图表
}
/** tab end */

/** card start */
const cardActiveItem: any = ref({})
const topCard = reactive([
  {
    id: '1',
    title: '监控点位总数',
    content: '0',
    imgUrl: jkdwzs,
    textColor: '#6566FF',
    bckColor: '#DFDFFF',
    dm: '',
  },
  {
    id: '2',
    title: '正常点位',
    content: '0',
    imgUrl: zcdw,
    textColor: '#00CD99',
    bckColor: '#E7FFFB',
    dm: 1,
  },
  {
    id: '3',
    title: '告警点位',
    content: '0',
    imgUrl: jgdw,
    textColor: '#FF6666',
    bckColor: '#FFECEA',
    dm: 2,
  },
  {
    id: '4',
    title: '离线点位',
    content: '0',
    imgUrl: lxdw,
    textColor: '#666666',
    bckColor: '#EDEDED',
    dm: 3,
  },
])

//加载监测点位数量
function loadJcdwInfo() {
  //能源类型查询监测点位数量
  queryJcdwTjInfoList({ nylx: nylx.value }).then((res: any) => {
    topCard[0].content = res.jkdwzs
    topCard[1].content = res.zcdwsl
    topCard[2].content = res.gjdwsl
    topCard[3].content = res.lxdwsl
  })
}
loadJcdwInfo()

const dialogVisible = ref(false)
const tabCardClick = (item: any) => {
  cardActiveItem.value = item

  pageNo.value = 1
  pageSize.value = 10
  getTableData() //查询表格数据
  dialogVisible.value = true
}
/** card end */

/** tree start */
const treeRef = ref(null) as any
const defaultProps = {
  children: 'jcdwList',
  label: 'mc',
}
const treeData: any = ref([])
//加载企业信息
function getQylb() {
  //查询企业列表
  queryQylb({ nylx: nylx.value }).then((res: any) => {
    treeData.value = res?.map((item: any) => {
      const children = item?.jcdwList?.map((i: any) => {
        i.mc = i.dwmc
        return {
          ...i,
        }
      })

      return {
        ...item,
        mc: item.qymc,
        children,
      }
    })

    if (treeData.value.length > 0) {
      if (treeData.value[0].children && treeData.value[0].children.length > 0) {
        formInline.mbId = treeData.value[0].children[0].id
        formInline.ssqyMc = treeData.value[0].children[0].ssqyMc
      }

      treeRef.value.defaultActive(treeData.value[0].id) //默认展开高亮操作

      treeClick(treeData.value[0], null)
    }
  })
}
getQylb()

//节点点击事件
const echartsLegendText = ref('')
const treeClick = (data: any, node: any) => {
  //点位
  if (!('wd' in data)) {
    formInline.mblx = 2
    formInline.mbId = data.id
    formInline.ssqyMc = data.ssqyMc

    queryZdInfo({ zdxdm: topNav[tabActiveIndex.value].xzcs }).then((res) => {
      xzcsOption.value = res
      //图表Legend文字
      echartsLegendText.value = `${data.ssqyMc}-${data.mc.replace(data.ssqyMc, '')}-${data.dwbh}`

      loadEchat()
    })
  }
  //企业
  else {
    formInline.mbId = data.id
    formInline.mblx = 1

    //图表Legend文字
    echartsLegendText.value = `${data.mc}`

    //企业的选择参数只能为有功功率 or 正向有功
    if (formInline.xzcs !== '1' && formInline.xzcs !== '8') {
      formInline.xzcs = '1'
    }

    xzcsOption.value = xzcsOption.value.filter(
      (item) => item.mc === '有功功率' || item.mc === '正向有功'
    )

    loadEchat()
  }
}
/** tree end */

/** 查询字典项 start */
const formInline = reactive({
  xzcs: '3', //选择参数
  sjfw: [
    moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    moment().format('YYYY-MM-DD HH:mm:ss'),
  ],
  szlx: '1', //数值类型
  jgsj: '', //时间间隔

  mbId: '',
  mblx: 1,

  ssqyMc: '',
})

const xzcsOption: any = ref([]) //选择参数
const szlxOption: any = ref([]) //数值类型
const sjjgOption: any = ref([]) //时间间隔
const jclxOption: any = ref([]) //监测类型
function getDictionary() {
  queryZdInfo({ zdxdm: 'szlx' }).then((res) => {
    szlxOption.value = res
    formInline.szlx = res[0].dm
  })
  querySjjgZdInfo({
    nylx: nylx.value,
    startTime: formInline.sjfw[0],
    endTime: formInline.sjfw[1],
    szlx: formInline.szlx,
  }).then((res) => {
    sjjgOption.value = res
    formInline.jgsj = res[0].dm
  })
  queryZdInfo({ zdxdm: topNav[tabActiveIndex.value].xzcs }).then((res) => {
    xzcsOption.value = res
    formInline.xzcs = res[0].dm
  })
  queryZdInfo({ zdxdm: 'jclx' }).then((res: any) => {
    jclxOption.value = res
  })
}
getDictionary()
/** 查询字典项 end */

/** echarts start */
const echartRef = ref(null) as any

const chartOption = reactive({
  graphic: [
    {
      type: 'text',
      left: 'center',
      top: 'middle',
      style: {
        fill: '#999',
        text: '暂无数据',
        font: '14px Microsoft YaHei',
      },
    },
  ],
  title: {
    text: '',
    textStyle: {
      fontWeight: 'normal',
    },
    left: 'center',
    // top: 'center',
  },
  legend: {
    left: 'left',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      animation: false,
    },
    backgroundColor: 'rgba(16,16,52,0.6)',
    textStyle: {
      color: 'white',
    },
    formatter: function (params: any) {
      const data = params[0].data.value
      const time = new Date(data[0]).toLocaleString()
      const value = data[1]
      return `时&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;间：${time}<br/>有功功率：${value}kW`
    },
  },
  xAxis: {
    type: 'time',
    splitLine: {
      show: false,
    },
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, '100%'],
    splitLine: {
      show: true,
    },
  },
  series: [
    {
      name: '',
      type: 'line',
      showSymbol: false,
      itemStyle: {
        normal: {
          color: '#3AB779',
          lineStyle: {
            color: '#3AB779',
          },
        },
      },
      data: [],
    },
  ],
})

// 定义搜索时间间隔（以毫秒为单位）
const intervals = {
  1: 5 * 60 * 1000, //5分钟
  2: 15 * 60 * 1000, //15分钟
  3: 60 * 60 * 1000, //1小时
}

// 保存定时器ID
let timerId = null

onMounted(() => {
  echartRef.value.initEchat(chartOption)
})
//查询图表数据
function queryEchartData() {
  const params = {
    xzcs: formInline.xzcs, //选择参数
    startTime: formInline.sjfw[0],
    endTime: formInline.sjfw[1],
    szlx: formInline.szlx,
    jgsj: formInline.jgsj,
    mbId: formInline.mbId,
    nylx: Number(nylx.value),
    mblx: formInline.mblx, //目标类型
    ymlx: 1, //查询页面类型
  }

  chartOption.graphic = [
    {
      type: 'text',
      left: 'center',
      top: 'middle',
      style: {
        fill: '#999',
        text: '加载中...',
        font: '14px Microsoft YaHei',
      },
    },
  ]
  chartOption.title.text = ''
  chartOption.series[0].name = ''
  chartOption.series[0].data = []
  echartRef.value.initEchat(chartOption)

  queryJcdwTbInfo(params)
    .then((res: any) => {
      const data =
        (res.dwHistoryResp &&
          res.dwHistoryResp.sjList &&
          res.dwHistoryResp.sjList.map((item: any, index: any) => {
            return { value: [item, res.dwHistoryResp.dwHistoryInfoList[0].ylz[index]] }
          })) ||
        []

      if (res.dwHistoryResp) {
        chartOption.title.text =
          res.dwHistoryResp.dwHistoryInfoList[0].ylx +
          '/' +
          res.dwHistoryResp.dwHistoryInfoList[0].ylxDw
        chartOption.series[0].name = `${echartsLegendText.value}——${res.dwHistoryResp.dwHistoryInfoList[0].ylx}`
        chartOption.series[0].data = data
      }

      chartOption.tooltip.formatter = function (params: any) {
        const data = params[0].data.value
        const time = new Date(data[0]).toLocaleString()
        const value = data[1]
        return `时&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;间：${time}<br/>${res.dwHistoryResp.dwHistoryInfoList[0].ylx}：${value}${res.dwHistoryResp.dwHistoryInfoList[0].ylxDw}`
      }

      if (data.length < 1) {
        chartOption.graphic = [
          {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              fill: '#999',
              text: '暂无数据',
              font: '14px Microsoft YaHei',
            },
          },
        ]
      } else {
        chartOption.graphic = null
      }

      echartRef.value.initEchat(chartOption)
    })
    .catch(() => {
      chartOption.graphic = [
        {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            fill: '#999',
            text: '加载失败',
            font: '14px Microsoft YaHei',
          },
        },
      ]
      echartRef.value.initEchat(chartOption)
    })
}

// 清除定时器
function clearTimer() {
  if (timerId) {
    clearInterval(timerId)
    timerId = null
    console.log('已清除定时查询')
  }
}

function loadEchat() {
  clearTimer()

  queryEchartData()

  //结束时间为今天 并且 搜索时间间隔为15分钟或1小时 执行”定时查询“
  if (
    moment(formInline.sjfw[1]).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD') &&
    intervals[formInline.jgsj]
  ) {
    console.log('已设置定时查询,间隔时间为:' + intervals[formInline.jgsj] / (60 * 1000) + '分钟')

    // 设置定时查询
    timerId = setInterval(function () {
      queryEchartData()
    }, intervals[formInline.jgsj])
  }
}

onBeforeUnmount(() => {
  clearTimer()
})

//修改时间和数值类型时 重新查询时间间隔
const dateAndSjlxChange = () => {
  formInline.sjfw[0] = moment(formInline.sjfw[0]).format('YYYY-MM-DD HH:mm:ss')
  formInline.sjfw[1] = moment(formInline.sjfw[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
  querySjjgZdInfo({
    nylx: nylx.value,
    startTime: formInline.sjfw[0],
    endTime: formInline.sjfw[1],
    szlx: formInline.szlx,
  }).then((res) => {
    sjjgOption.value = res
    formInline.jgsj = res[0].dm
  })
}

//重置echarts
const resetEchart = () => {
  formInline.szlx = szlxOption.value[0].dm
  formInline.sjfw = [
    moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    moment().format('YYYY-MM-DD HH:mm:ss'),
  ]
  formInline.xzcs = xzcsOption.value[0].dm
  formInline.szlx = szlxOption.value[0].dm

  querySjjgZdInfo({
    nylx: nylx.value,
    szlx: formInline.szlx,
    startTime: formInline.sjfw[0],
    endTime: formInline.sjfw[1],
  }).then((res) => {
    sjjgOption.value = res
    formInline.jgsj = res[0].dm

    loadEchat()
  })
}
/** echarts end */

/** table start */
// 定义列配置
const tableColumns = [
  {
    label: '序号',
    width: '80',
    type: 'index',
  },
  {
    prop: 'dwmc',
    label: '监测点位名称',
  },
  {
    prop: 'dwbh',
    label: '监测点位编号',
  },
  {
    prop: 'ssqyMc',
    label: '所属企业名称',
    width: '230',
  },
  {
    prop: 'ssqyQydz',
    label: '所在地址',
  },
  {
    label: '经纬度',
    slotName: 'jwdColumn',
    type: 'slot',
    width: '200',
    align: 'center',
  },
  {
    prop: 'gldwMc',
    label: '管理单位',
  },
  {
    prop: 'gldwLxrxm',
    label: '联系人',
  },
  {
    prop: 'gldwLxrdh',
    label: '联系电话',
  },
  {
    label: '监测状态',
    slotName: 'jcztColumn',
    type: 'slot',
  },
  {
    slotName: 'jclxColumn',
    type: 'slot',
    label: '监测类型',
  },
  {
    label: '操作',
    width: '140',
    slotName: 'actionColumn',
    type: 'slot',
    align: 'center',
  },
]

//处理监测类型
const formatJclx = computed(() => {
  return (val: any) => {
    if (val) {
      let result = ''
      jclxOption.value.forEach((item: any) => {
        if (item.dm == val) {
          result = item.mc
        }
      })
      return result
    }
    return ''
  }
})

//搜索参数
const pageNo = ref(1)
const pageSize = ref(10)
const tableTotal = ref(0)
const tableData: any = ref([])
function getTableData() {
  const data: any = {
    nylx: nylx.value,
    jczt: cardActiveItem.value.dm,
    pageNo: pageNo.value,
    pageSize: pageSize.value,
  }
  queryJcdwInfoList(data).then((res: any) => {
    tableData.value = res.records
    pageNo.value = res.current
    pageSize.value = res.size
    tableTotal.value = res.total
  })
}

//分页操作
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val: number) => {
  pageNo.value = val
  getTableData()
}

/** table end */

//监测点位弹窗信息
const dialogShow = ref(false)
const inputDisabled = ref(true)

const jcdwFormList = [
  {
    formLabelWidth: '160px',
    formList: [
      {
        prop: 'dwmc',
        label: '监测点位名称',
        type: 'input',
        value: '',
      },
      {
        prop: 'dwbh',
        label: '监测点位编号',
        type: 'input',
        value: '',
      },
      {
        prop: 'ssqyMc',
        label: '所属企业名称',
        type: 'input',
        value: '',
      },
      {
        prop: 'ssqyQydz',
        label: '所在地址',
        type: 'input',
        value: '',
      },
      {
        prop: 'jwd',
        label: '经纬度',
        type: 'input',
        value: '',
      },
      {
        prop: 'gldwMc',
        label: '管理单位',
        type: 'input',
        value: '',
      },
      {
        prop: 'gldwLxrdh',
        label: '联系电话',
        type: 'input',
        value: '',
      },
      {
        prop: 'jczt',
        label: '监测状态',
        type: 'input',
        value: '',
      },
      {
        prop: 'jclx',
        label: '监测类型',
        type: 'input',
        value: '',
      },
    ],
  },
]

//查询检测点位信息
const query = (row: any) => {
  queryJcdwInfo({ jcdwId: row.id }).then((res: any) => {
    for (const key in res) {
      jcdwFormList[0].formList.forEach((item: any) => {
        if (key === item.prop) {
          if (key === 'jczt') {
            item.value = res[key] === 1 ? '正常' : res[key] === 2 ? '告警' : '离线'
          } else if (key === 'jclx') {
            item.value = res[key]
            jclxOption.value.forEach((jclx: any) => {
              if (jclx.dm == item.value) {
                item.value = jclx.mc
              }
            })
          } else {
            item.value = res[key]
          }
        }
      })
    }

    jcdwFormList[0].formList.forEach((item: any) => {
      if (item.prop === 'jwd' && res.ssqyJd && res.ssqyWd) {
        item.value = res.ssqyJd + ',' + res.ssqyWd
      }
    })

    inputDisabled.value = true
    dialogShow.value = true
  })
}

const deleteData = () => {
  ElMessageBox.confirm('暂无权限操作!', '提示', {
    confirmButtonText: '确认',
    type: 'warning',
    showCancelButton: false,
  }).then(() => { })
}
</script>

<template>
  <!-- tab -->
  <div class="flex items-center h-60px pl-10px bg-[#f8f8f8]">
    <div v-for="(item, index) in topNav" :key="index"
      class="w-150px h-36px lh-36px mr-10px text-center text-[#333] bg-[#dceeff] rounded-18px cursor-pointer"
      :class="{ 'tab-active': tabActiveIndex === index }" @click="tabClick(item, index)">
      {{ item.text }}
    </div>
  </div>

  <div class="p-10px pt-0 pb-8px box-border" style="height: calc(100% - 100px)">
    <!-- top -->
    <div class="flex flex-row justify-between items-center h-180px">
      <div v-for="item in topCard" :key="item.id"
        class="flex justify-between items-center w-25% h-118px mr-32px cursor-pointer topCard"
        :style="{ backgroundColor: item.bckColor }" @click="tabCardClick(item)">
        <img class="w-80px h-80px ml-22px" style="object-fit: contain" :src="item.imgUrl" alt="" />
        <div class="text-right h-107px mr-46px">
          <div class="text-63px lh-36px mt-20px font-normal" :style="{ color: item.textColor }"
            style="font-family: 'CenturyGothic'">
            {{ item.content }}
          </div>
          <div class="text-24px text-[#333] mt-12px font-normal" :style="{ color: item.textColor }">
            {{ item.title }}
          </div>
        </div>
      </div>
    </div>

    <!-- bottom -->
    <div v-show="dialogVisible === false" class="flex flex-row" style="height: calc(100% - 180px)">
      <div class="w-330px box-border" style="box-shadow: 0px 1px 10px 0px rgba(153, 153, 153, 0.4)">
        <!-- 企业列表 -->
        <EnterpriseList ref="treeRef" :tree-data="treeData" :default-props="defaultProps" @tree-click="treeClick">
        </EnterpriseList>
      </div>

      <!-- content -->
      <div class="flex-1 flex flex-col h-100% ml-10px">
        <div class="h-140px p-40px box-border" style="box-shadow: 0px 1px 10px 0px rgba(153, 153, 153, 0.4)">
          <el-form :inline="true" class="flex justify-between">
            <el-form-item label="选择参数">
              <el-select v-model="formInline.xzcs" placeholder="请选择参数" class="w-160px">
                <el-option v-for="item in xzcsOption" :key="item.id" :label="item.mc" :value="item.dm" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择时间范围">
              <el-date-picker v-model="formInline.sjfw" type="daterange" format="YYYY-MM-DD" range-separator="至"
                unlink-panels start-placeholder="开始时间" end-placeholder="结束时间" @change="dateAndSjlxChange" />
            </el-form-item>
            <el-form-item label="数值类型">
              <el-select v-model="formInline.szlx" placeholder="请选择数值类型" class="w-160px" @change="dateAndSjlxChange">
                <el-option v-for="item in szlxOption" :key="item.id" :label="item.mc" :value="item.dm" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间间隔" style="margin-right: 0">
              <el-select v-model="formInline.jgsj" placeholder="请选择时间间隔" class="w-160px">
                <el-option v-for="item in sjjgOption" :key="item.id" :label="item.mc" :value="item.dm" />
              </el-select>
            </el-form-item>
          </el-form>

          <div class="mt-2px text-right">
            <!-- <el-button class="w-80px text-[#fff] bg-[#0099ff] rounded-15px" @click="loadEchat"
              >查询</el-button
            >
            <el-button class="w-80px bg-[#dceeff] rounded-15px" @click="resetEchart"
              >重置</el-button
            > -->

            <el-button type="primary" class="w-80px rounded-15px" :icon="Search" @click="loadEchat">查询</el-button>
            <el-button class="w-80px bg-[#dceeff] rounded-15px" :icon="Refresh" @click="resetEchart">重置</el-button>
          </div>
        </div>

        <!-- echarts -->
        <div class="mt-10px" style="flex: 1; box-shadow: 0px 1px 10px 0px rgba(153, 153, 153, 0.4)">
          <!-- 折线图 -->
          <Echarts ref="echartRef" />
        </div>
      </div>
    </div>

    <!-- table -->
    <div v-if="dialogVisible" style="height: calc(100% - 180px)">
      <el-button type="primary" class="w-80px m-20px mt-0 rounded-15px" :icon="ArrowLeftBold"
        @click="dialogVisible = false">返回</el-button>

      <Table class="mt-20px" style="height: calc(100% - 120px)" :table-columns="tableColumns" :table-data="tableData">
        <template #jwdColumn="{ row }">
          <span>
            {{ (row.ssqyJd ? row.ssqyJd + ', ' : '') + (row.ssqyWd ? row.ssqyWd : '') }}
          </span>
        </template>

        <template #jcztColumn="{ row }">
          <span>
            {{ row.jczt === 1 ? '正常' : row.jczt === 2 ? '告警' : '离线' }}
          </span>
        </template>

        <template #jclxColumn="{ row }">
          <span>
            <span>{{ formatJclx(row.jclx) }}</span>
          </span>
        </template>

        <template #actionColumn="{ row }">
          <div class="flex justify-center">
            <el-button link type="primary" @click="query(row)">查看</el-button>
            <el-button link type="danger" @click="deleteData">删除</el-button>
          </div>
        </template>
      </Table>
      <el-pagination class="justify-end m-10px mt-15px" layout="total, sizes, prev, pager, next" :total="tableTotal"
        background @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>

  <Dialog :visible="dialogShow" title="监测点位详情查看" width="1000px" @close="dialogShow = false">
    <el-form v-for="(formItem, formIndex) in jcdwFormList" :key="formIndex" :label-width="formItem.formLabelWidth">
      <el-row :gutter="0">
        <el-col v-for="(item, index) in formItem.formList" :key="index" :span="item.span || 12">
          <el-form-item :label="item.label">
            <el-input v-model="item.value" :type="item.type" :disabled="inputDisabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </Dialog>
</template>

<style scoped>
.tab-active {
  font-size: 16px;
  font-weight: 700;
  color: #fff !important;
  background-color: #1990ff !important;
}

.topCard:nth-child(1) {
  box-shadow: 0px 1px 8px 0px rgba(153, 153, 153, 0.5), 0px 2px 4px 0px rgba(11, 31, 41, 0.3);
}

.topCard:nth-child(2) {
  box-shadow: 0px 1px 8px 0px rgba(153, 153, 153, 0.42), 0px 1px 0px 0px rgba(255, 255, 255, 0.6);
}

.topCard:nth-child(3) {
  box-shadow: 0px 1px 8px 0px rgba(153, 153, 153, 0.42), 0px 1px 0px 0px rgba(255, 255, 255, 0.6);
}

.topCard:nth-child(4) {
  box-shadow: 0px 1px 8px 0px rgba(153, 153, 153, 0.42), 0px 1px 0px 0px rgba(255, 255, 255, 0.6);
  margin-right: 0;
}

.el-tree {
  color: #333;
  font-size: 14px;
}
</style>
